package com.wwm.findit;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.util.Attributes;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class AccountActivity extends Activity {

	private ListView mListView;
	private VerticalListViewAdapter mAdapter;

	public static AccountActivity mInstance = null;

	private RequestQueue mRequestQueue;

	TextView textviewWealth;
	TextView textviewLevel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);

		mInstance = this;

        Button btn_add=(Button)findViewById(R.id.button_add);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("android.intent.action.ObjectActivity");
                startActivity(intent);
            }
        });

        Button btn_return = (Button)findViewById(R.id.button_account_return);
        btn_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AccountActivity.this.finish();
            }
        });


		TextView textviewName = (TextView)findViewById(R.id.textview_name);
		textviewLevel = (TextView)findViewById(R.id.textview_level);
		textviewWealth = (TextView)findViewById(R.id.textview_wealth);

		textviewName.setText("账号：" + GlobalData.username);
		textviewLevel.setText("等级：" + Integer.toString(GlobalData.userLevel) + "级");
		textviewWealth.setText("财富：" + Integer.toString(GlobalData.userWealth) + "亨特");


		mListView = (ListView) findViewById(R.id.listview_wait_publish);
		mAdapter = new VerticalListViewAdapter(this);

		//get data
//		ArrayList<Item> itemArray = new ArrayList<Item>();
//		Log.i("FindIt", "new");
//		itemArray.add(new Item("a", "a", 0, 0));
//		itemArray.add(new Item("c", "c", 1, 1));
//		itemArray.add(new Item("b", "b", 2, 2));
//		itemArray.add(new Item("d", "d", 3, 3));
//
//		mAdapter.setData(itemArray);

		mRequestQueue = Volley.newRequestQueue(this);
		Map<String, String> map = new HashMap<String, String>();
		map.put("username", GlobalData.username);

		JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.GET_ITEM_NOT_CONFIRM_URL, new JSONObject(map), new Response.Listener<JSONObject>()
		{
			@Override
			public void onResponse(JSONObject response)
			{
				Log.i("FindIt", response.toString());
				//parseJSON(response);
				//petIDArray = new ArrayList<Integer>();
				ArrayList<Item> itemArray = new ArrayList<Item>();


				try {
					Iterator it = response.keys();
					while (it.hasNext()) {
						String key = (String) it.next();
						String value = response.getString(key);
						JSONObject j = response.getJSONObject(key);
						Item p = new Item(j);
						itemArray.add(p);
						//petIDArray.add(Integer.parseInt(value));
					}

					mAdapter.setData(itemArray);
					mAdapter.notifyDataSetChanged();
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener()
		{
			@Override
			public void onErrorResponse(VolleyError error)
			{
				Log.i("FindIt", error.getMessage());
			}
		});
		mRequestQueue.add(jr);

		mListView.setAdapter(mAdapter);
		mAdapter.setMode(Attributes.Mode.Single);

		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				((SwipeLayout) (mListView.getChildAt(position - mListView.getFirstVisiblePosition()))).open(true);
			}
		});


		mListView.setOnTouchListener(new View.OnTouchListener()
		{
			@Override
			public boolean onTouch(View v, MotionEvent event)
			{
				Log.e("ListView", "OnTouch");
				return false;
			}
		});


		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				Log.e("ListView", "onScrollStateChanged");
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

			}
		});


		mListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				Log.e("ListView", "onItemSelected:" + position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				Log.e("ListView", "onNothingSelected:");
			}
		});
    }

	@Override
	public void onResume()
	{
		super.onResume();

		Map<String, String> map = new HashMap<String, String>();
		map.put("username", GlobalData.username);

		JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.GET_ITEM_NOT_CONFIRM_URL, new JSONObject(map), new Response.Listener<JSONObject>()
		{
			@Override
			public void onResponse(JSONObject response)
			{
				Log.i("FindIt", response.toString());
				//parseJSON(response);
				//petIDArray = new ArrayList<Integer>();
				ArrayList<Item> itemArray = new ArrayList<Item>();


				try {
					Iterator it = response.keys();
					while (it.hasNext()) {
						String key = (String) it.next();
						String value = response.getString(key);
						JSONObject j = response.getJSONObject(key);
						Item p = new Item(j);
						itemArray.add(p);
						//petIDArray.add(Integer.parseInt(value));
					}

					mAdapter.setData(itemArray);
					mAdapter.notifyDataSetChanged();
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener()
		{
			@Override
			public void onErrorResponse(VolleyError error)
			{
				Log.i("FindIt", error.getMessage());
			}
		});
		mRequestQueue.add(jr);

		map = new HashMap<String, String>();
		map.put("name", GlobalData.username);
		jr = new JsonObjectRequest(Request.Method.POST, GlobalData.GET_USER_INFO_URL, new JSONObject(map), new Response.Listener<JSONObject>()
		{
			@Override
			public void onResponse(JSONObject response)
			{
				Log.i("FindIt", response.toString());
				try{
				int retVal = response.getInt("success");
				if (retVal == 0)
				{
					GlobalData.userWealth = response.getInt("allMoneny");
					GlobalData.userLevel = response.getInt("level");
					textviewLevel.setText("等级：" + Integer.toString(GlobalData.userLevel) + "级");
					textviewWealth.setText("财富：" + Integer.toString(GlobalData.userWealth) + "亨特");
				}
				else
				{

				}}
				catch (JSONException e)
				{}
			}
		}, new Response.ErrorListener()
		{
			@Override
			public void onErrorResponse(VolleyError error)
			{
				Log.i("FindIt", error.getMessage());
			}
		});
		mRequestQueue.add(jr);
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_account, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
